<template>
  <div v-if="showPlayer" class="audio-player fixed bottom-0 left-0 right-0 bg-white shadow-lg border-t border-gray-200 z-40">
    <div class="max-w-4xl mx-auto px-4 py-4">
      <div class="flex items-center space-x-4">
        <!-- 播放/暂停按钮 -->
        <button 
          @click="togglePlayPause"
          class="btn-icon focus-ring"
          :class="{ 'bg-accent-green': isPlaying }"
        >
          <img 
            :src="isPlaying ? '/images/icon_pause_8.jpg' : '/images/icon_play_4.jpg'" 
            :alt="isPlaying ? '暂停' : '播放'"
            class="w-6 h-6"
          />
        </button>
        
        <!-- 进度条 -->
        <div class="flex-1">
          <div class="flex items-center space-x-2">
            <span class="text-sm text-text-secondary min-w-[3rem]">
              {{ formatTime(currentTime) }}
            </span>
            
            <div class="flex-1 relative">
              <div class="h-2 bg-gray-200 rounded-full overflow-hidden">
                <div 
                  class="h-full bg-gradient-to-r from-primary-coral to-primary-orange rounded-full transition-all duration-300"
                  :style="{ width: `${progress}%` }"
                ></div>
              </div>
              
              <!-- 滑块 -->
              <div 
                class="absolute top-1/2 transform -translate-y-1/2 w-5 h-5 bg-white rounded-full shadow-lg cursor-pointer border-2 border-primary-coral transition-all duration-300 hover:scale-110"
                :style="{ left: `calc(${progress}% - 10px)` }"
                @mousedown="startSeek"
                @touchstart="startSeek"
              ></div>
            </div>
            
            <span class="text-sm text-text-secondary min-w-[3rem]">
              {{ formatTime(duration) }}
            </span>
          </div>
        </div>
        
        <!-- 速度控制 -->
        <div class="flex items-center space-x-2">
          <button 
            @click="setSpeed(0.5)"
            class="px-3 py-1 text-sm rounded-full transition-colors"
            :class="speed === 0.5 
              ? 'bg-primary-coral text-white' 
              : 'bg-gray-100 text-text-secondary hover:bg-gray-200'"
          >
            0.5x
          </button>
          <button 
            @click="setSpeed(1.0)"
            class="px-3 py-1 text-sm rounded-full transition-colors"
            :class="speed === 1.0 
              ? 'bg-primary-coral text-white' 
              : 'bg-gray-100 text-text-secondary hover:bg-gray-200'"
          >
            1.0x
          </button>
          <button 
            @click="setSpeed(1.5)"
            class="px-3 py-1 text-sm rounded-full transition-colors"
            :class="speed === 1.5 
              ? 'bg-primary-coral text-white' 
              : 'bg-gray-100 text-text-secondary hover:bg-gray-200'"
          >
            1.5x
          </button>
        </div>
        
        <!-- 循环按钮 -->
        <button 
          @click="toggleLoop"
          class="btn-icon focus-ring"
          :class="{ 'bg-accent-yellow': isLooping }"
        >
          <span class="text-white text-sm font-bold">∞</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useAudioStore } from '@/stores/audio'
import { useRoute } from 'vue-router'

const route = useRoute()
const audioStore = useAudioStore()

const showPlayer = computed(() => route.name === 'poetry-detail')
const isPlaying = computed(() => audioStore.audioState.isPlaying)
const speed = computed(() => audioStore.audioState.speed)
const isLooping = computed(() => audioStore.audioState.isLooping)

// 模拟时间和进度
const currentTime = ref(0)
const duration = ref(180) // 默认3分钟
const progress = computed(() => duration.value > 0 ? (currentTime.value / duration.value) * 100 : 0)

let seekInterval: number | null = null

// 播放/暂停切换
const togglePlayPause = () => {
  audioStore.togglePlayPause()
  if (isPlaying.value) {
    startProgressTracking()
  } else {
    stopProgressTracking()
  }
}

// 设置播放速度
const setSpeed = (newSpeed: number) => {
  audioStore.setSpeed(newSpeed)
}

// 切换循环播放
const toggleLoop = () => {
  audioStore.toggleLoop()
}

// 开始进度追踪
const startProgressTracking = () => {
  stopProgressTracking()
  seekInterval = window.setInterval(() => {
    currentTime.value += 1
    if (currentTime.value >= duration.value) {
      if (!isLooping.value) {
        audioStore.pause()
        currentTime.value = 0
      } else {
        currentTime.value = 0
      }
      stopProgressTracking()
    }
  }, 1000)
}

// 停止进度追踪
const stopProgressTracking = () => {
  if (seekInterval) {
    clearInterval(seekInterval)
    seekInterval = null
  }
}

// 开始拖拽进度条
const startSeek = (event: MouseEvent | TouchEvent) => {
  stopProgressTracking()
  
  const updateProgress = (clientX: number) => {
    const rect = (event.target as Element).getBoundingClientRect()
    const x = clientX - rect.left
    const progress = Math.max(0, Math.min(1, x / rect.width))
    currentTime.value = Math.round(progress * duration.value)
  }
  
  const handleMouseMove = (e: MouseEvent) => {
    updateProgress(e.clientX)
  }
  
  const handleTouchMove = (e: TouchEvent) => {
    if (e.touches[0]) {
      updateProgress(e.touches[0].clientX)
    }
  }
  
  const handleEnd = () => {
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('touchmove', handleTouchMove)
    document.removeEventListener('mouseup', handleEnd)
    document.removeEventListener('touchend', handleEnd)
    
    if (isPlaying.value) {
      startProgressTracking()
    }
  }
  
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('touchmove', handleTouchMove)
  document.addEventListener('mouseup', handleEnd)
  document.addEventListener('touchend', handleEnd)
}

// 格式化时间
const formatTime = (seconds: number): string => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins}:${secs.toString().padStart(2, '0')}`
}

onMounted(() => {
  // 监听路由变化，初始化音频
  if (route.name === 'poetry-detail') {
    const poemId = parseInt(route.params.id as string)
    // 在实际实现中，这里应该传递真实的古诗文本
    audioStore.initAudio('古诗文本', poemId)
  }
})

onUnmounted(() => {
  stopProgressTracking()
})
</script>

<style scoped>
.audio-player {
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .audio-player {
    padding: 8px 0;
  }
  
  .audio-player .flex {
    gap: 8px;
  }
}
</style>